package com.zx.config.listener;

import com.zx.link.entity.LinkType;
import com.zx.link.service.LinkTypeService;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import javax.servlet.ServletContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import org.springframework.web.context.ServletContextAware;


/**
 * 系统初始化，加载器
 *
 * @author zhangx
 */
@Component
@Slf4j
public class SystemInitBean implements ServletContextAware {

    /****静态资源****/
    public static byte[] DEFAUTL_IMG_BIN = null;

    public static List<LinkType> LINK_TYPES = null;

    /****业务实例****/
    @Autowired
    private LinkTypeService linkTypeService;

    /**
     * 应用启动数据初始化入口
     */
    @Override
    public void setServletContext(ServletContext app) {
        Object object = app.getAttribute("initFlag");
        if (object != null) {
            return;
        }
        app.setAttribute("initFlag", "true");
        log.info(
                "**************************************************系统准备开启************************************************************");
        log.info("[个人管理系统开启中，正在初始化数据]");
        try {
            this.initImg(app);
            this.getTypes();
            log.info("[初始化完毕，个人管理系统已经开启]");
        } catch (Exception e) {
            log.error("[初始化失败！！]", e);

        }
    }

    /**
     * 初始化图片
     *
     * @param app
     */
    private void initImg(ServletContext app) {
        InputStream is = null;
        try {
            ClassPathResource classPathResource = new ClassPathResource("/static/imge/default-64x64.jpg");
            is = classPathResource.getInputStream();
            DEFAUTL_IMG_BIN = new byte[is.available()];
            is.read(DEFAUTL_IMG_BIN);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void getTypes() {
        LINK_TYPES = this.linkTypeService.getAll();
    }

}
